package jnpf.service.impl;


import cn.hutool.core.util.StrUtil;

import com.google.gson.Gson;
import com.jayway.jsonpath.JsonPath;
import jnpf.common.enums.dify.DifyApiEnum;
import jnpf.model.common.AnalyzeResult;
import jnpf.model.common.ModuleData;
import jnpf.model.common.TalkRequest;
import jnpf.model.dify.talk.req.*;
import jnpf.model.dify.talk.resp.*;
import jnpf.model.dify.talk.talkReq.DoCreateReq;
import jnpf.model.dify.talk.talkReq.ModuleCreateReq;
import jnpf.service.DifyTalkService;
import jnpf.util.DifyApiReqUtil;
import jnpf.util.JsonUtils;
import jnpf.util.ResultHandleUtil;
import jnpf.util.UserProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author zpw
 */
@Service
@Slf4j
public class DifyTalkServiceImpl implements DifyTalkService {
    @Value("${dify.url:}")
    public String API_BASE_URL;

    @Value("${dify.talk.manage_module_create_ai:}")
    public String manageModuleCreateAI;
    @Value("${dify.talk.tech_module_create_ai:}")
    public String techModuleCreateAI;
    @Value("${dify.talk.do_create_ai:}")
    public String doCreateAI;
    @Value("${dify.talk.manage_module_talk_ai:}")
    public String manageModuleTalkAI;
    @Value("${dify.talk.tech_module_talk_ai:}")
    public String techModuleTalkAI;
    @Value("${dify.talk.manage_do_talk_ai:}")
    public String manageDoTalkAI;
    @Value("${dify.talk.tech_do_talk_ai:}")
    public String techDoTalkAI;
    @Value("${dify.talk.knowledge_base_talk_ai:}")
    public String knowledgeBaseTalkAI;
    @Value("${dify.talk.doc_analyze_ai:}")
    public String docAnalyzeAi;

    @Autowired
    public UserProvider userProvider;


    @Override
    public Flux<String> streamTalkAI(TalkRequest talkRequest)  {
        Integer aiTypeId = talkRequest.getAiTypeId();
        AiParamReq queryBody = getQueryBody(talkRequest);
        return DifyApiReqUtil.sendStreamingRequest(API_BASE_URL + DifyApiEnum.CREATE_CHAT_MESSAGE.getApi(),getKey(aiTypeId), queryBody).onBackpressureBuffer();
    }

    /**
     * 阻塞AI对话
     */
    @Deprecated
    public AnalyzeResult docTalkAi(FlowTalkReq flowTalkReq, Integer aiTypeId)   {
        String txt = null;
        try {
            txt = DifyApiReqUtil.sendApiReq(API_BASE_URL,  getKey(aiTypeId), DifyApiEnum.WORK_FLOW, null, flowTalkReq, userProvider.get().getUserId());
        } catch (IOException e) {
            return AnalyzeResult.error(e.getMessage());
        }
        String[] split = txt.split("\n");
        List<String> list = new ArrayList<>();
        Collections.addAll(list, split);
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);

        }
        String thoughtJson = "";
        for (String res : list) {
            if (StrUtil.isEmpty(res)) {
                continue;
            }
            String resultString = res.trim().replaceFirst("^data:", "");
            if (JsonUtils.keyExists(resultString, "$.event")) {
                String event = JsonPath.read(resultString, "$.event");
              if ("workflow_finished".equals(event)) {
                    if (JsonUtils.keyExists(resultString, "$.data.status")) {
                        String statusValue = JsonPath.read(resultString, "$.data.status");
                        if (statusValue.equals("succeeded")) {
                            if (JsonUtils.keyExists(resultString, "$.data.outputs")) {
                                thoughtJson = JsonPath.read(resultString, "$.data.outputs.Result");
                            }
                        }else{
                            return AnalyzeResult.error("dify执行失败");
                        }
                    }
              }
            }
        }
        if (StrUtil.isEmpty(thoughtJson)) {
            return AnalyzeResult.error("未获取到解析结果");
        }else{
            AnalyzeResult analyzeResult = new AnalyzeResult();
            if(flowTalkReq.getInputs().getType().equals("DO名称列表解析")) {
//                log.info("do名称列表解析结果：{}",thoughtJson);
//                analyzeResult.setDoNameList(JsonUtils.convertJsonToNameList(thoughtJson));
//                analyzeResult.setWorkflowRunRequest(flowTalkReq);
//                analyzeResult.setTalkType(3);
                return analyzeResult;
            }else {
                log.info("do详情解析结果：{}",thoughtJson);
//                analyzeResult.setDoShowList(JsonUtils.convertJsonToMap(thoughtJson));
//                analyzeResult.setWorkflowRunRequest(flowTalkReq);
//                analyzeResult.setTalkType(4);
                return analyzeResult;
            }
        }
    }

    // 上传文件
    @Override
    public String  uploadFile(File file) throws Exception {
        return DifyApiReqUtil.sendFileRequest(API_BASE_URL+DifyApiEnum.UPLOAD_FILE.getApi(), docAnalyzeAi,   file,userProvider.get().getUserId());
    }

    // 终止对话，这里根据路径中需要task_id参数，所以添加进来
    @Override
    public String stopChat(String taskId) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("task_id", taskId);
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, manageModuleCreateAI, DifyApiEnum.STOP_CHAT, params,  new UserReq(),userProvider.get().getUserId());
    }

    // 消息点赞，这里根据路径中需要message_id参数，所以添加进来
    @Override
    public String likeMessage(String messageId, Map<String, Object> requestParams) throws Exception {
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, manageModuleCreateAI, DifyApiEnum.LIKE_MESSAGE, null, messageId, userProvider.get().getUserId());
    }

    // 获取下一轮建议问题列表，这里根据路径中需要message_id参数，所以添加进来
    @Override
    public String getSuggestedQuestions(String messageId, Map<String, Object> requestParams) throws Exception {
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, manageModuleCreateAI, DifyApiEnum.GET_SUGGESTED_QUESTIONS, null, messageId, userProvider.get().getUserId());
    }

    // 获取会话历史消息
    @Override
    public List<TalkHistoryResp> getChatHistoryMessages(String talkId, Integer aiType) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("conversation_id", talkId);
        params.put("user",  userProvider.get().getUserId());
        params.put("first_id", null);
        params.put("limit", "100");
        String s = DifyApiReqUtil.sendApiReq(API_BASE_URL, getKey(aiType), DifyApiEnum.GET_CHAT_HISTORY_MESSAGES, params, null, userProvider.get().getUserId());

        List<TalkHistoryResp> talkHistoryRespList=new ArrayList<>();
        Gson gson=new Gson();

        //提取对话信息，转为对话列表
        TalkHistory talkHistory = gson.fromJson(s, TalkHistory.class);
        List<TalkHistory.DataItem> data = talkHistory.getData();
        for (TalkHistory.DataItem dataItem : data) {
            TalkHistoryResp talkHistoryResp=new TalkHistoryResp();
            talkHistoryResp.setId(dataItem.getId());
            talkHistoryResp.setQuery(dataItem.getQuery());
            talkHistoryResp.setAnswer(dataItem.getAnswer());
            if(dataItem.getInputs()!=null){
                Map<String, String> inputs = dataItem.getInputs();
                talkHistoryResp.setInput(inputs);
            }
            talkHistoryRespList.add(talkHistoryResp);
        }
        return talkHistoryRespList;
    }

    // 获取会话列表
    @Override
    public List<DifyTalkListConvertResp> getConversationList(Integer aiType) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("user",  userProvider.get().getUserId());
        params.put("last_id", null);
        params.put("limit", "100");
        //请求返回内容
        String jsonResponse = DifyApiReqUtil.sendApiReq(API_BASE_URL, getKey(aiType), DifyApiEnum.GET_CONVERSATION_LIST, params, null, userProvider.get().getUserId());
        //转换
        Gson gson = new Gson();
        DifyTalkListResp difyTalkListResp = gson.fromJson(jsonResponse, DifyTalkListResp.class);
        //数据提取
        List<DifyTalkListResp.ConversationData> data = difyTalkListResp.getData();
        List<DifyTalkListConvertResp> difyTalkListConvertRespList = new ArrayList<>();
        if(data != null && data.size() > 0) {
            data.forEach(e -> {
                DifyTalkListConvertResp difyTalkListConvertResp=new DifyTalkListConvertResp();
                difyTalkListConvertResp.setId(e.getId());
                difyTalkListConvertResp.setName(e.getName());
                difyTalkListConvertRespList.add(difyTalkListConvertResp);
            });
        }
        return difyTalkListConvertRespList;
    }



    // 删除会话，这里根据路径中需要conversation_id参数，所以添加进来
    @Override
    public String deleteConversation(String conversationId, Integer aiType) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("conversation_id", conversationId);
        UserReq userReq = new UserReq();
        userReq.setUser( userProvider.get().getUserId());
        return DifyApiReqUtil.sendApiReq(API_BASE_URL,getKey(aiType), DifyApiEnum.DELETE_CONVERSATION, params, userReq, userProvider.get().getUserId());
    }

    // 会话重命名，这里根据路径中需要conversation_id参数，所以添加进来
    @Override
    public String renameConversation(ReNameReq reNameReq, Integer aiType) throws Exception {
        Map<String, String> params = new HashMap<>();
        params.put("conversation_id", reNameReq.getId());
        HandleTalkNameReq handleTalkNameReq = new HandleTalkNameReq();
        handleTalkNameReq.setName(reNameReq.getName());
        return  DifyApiReqUtil.sendApiReq(API_BASE_URL, getKey(aiType), DifyApiEnum.RENAME_CONVERSATION, params, handleTalkNameReq, userProvider.get().getUserId());
    }

    // 语音转文字
    @Override
    public String audioToText(Map<String, Object> requestParams) throws Exception {
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, manageModuleCreateAI, DifyApiEnum.AUDIO_TO_TEXT, null, null, userProvider.get().getUserId());
    }

    // 文字转语音
    @Override
    public String textToAudio(Map<String, Object> requestParams) throws Exception {
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, manageModuleCreateAI, DifyApiEnum.TEXT_TO_AUDIO, null, null, userProvider.get().getUserId());
    }

    // 获取应用配置信息
    @Override
    public String getAppParameters(UserReq userReq) throws Exception {
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, manageModuleCreateAI, DifyApiEnum.GET_APP_PARAMETERS, null, userReq, userProvider.get().getUserId());
    }

    // 获取应用Meta信息
    @Override
    public String getAppMeta(Map<String, Object> requestParams) throws Exception {
        return DifyApiReqUtil.sendApiReq(API_BASE_URL, manageModuleCreateAI, DifyApiEnum.GET_APP_META, null, null, userProvider.get().getUserId());
    }


    public static String getLongestStringUsingCollectionsMax(List<String> list) {
        if (list == null || list.isEmpty()) {
            return null;
        }
        return Collections.max(list, Comparator.comparingInt(String::length));
    }


    /**
     * 根据请求类型获取请求key
     */
    private String getKey(Integer aiType) {
        String defaultTxt = aiType+"对话AI：{}";
        if (aiType != null) {
            if (aiType == 1) {
                log.info(defaultTxt, "五力模型管理工程AI");
                return manageModuleCreateAI;
            } else if (aiType == 2) {
                log.info(defaultTxt, "五力模型技术工程AI");
                return techModuleCreateAI;
            } else if (aiType == 3) {
                log.info(defaultTxt, "DO创建AI");
                return doCreateAI;
            } else if (aiType == 4) {
                log.info(defaultTxt, "管理工程应答AI");
                return manageModuleTalkAI;
            } else if (aiType == 5) {
                log.info(defaultTxt, "技术工程应答AI");
                return techModuleTalkAI;
            } else if (aiType == 6) {
                log.info(defaultTxt, "管理工程应答AI");
                return manageDoTalkAI;
            } else if (aiType == 7) {
                log.info(defaultTxt, "技术工程应答AI");
                return techDoTalkAI;
            } else if (aiType == 8) {
                log.info(defaultTxt, "流式文档解析");
                return docAnalyzeAi;
            }
        }
        log.info(defaultTxt, "知识库应答AI");
        return knowledgeBaseTalkAI;
    }
    /**
     * 根据请求类型获取请求参数
     */
    private AiParamReq getQueryBody(TalkRequest talkRequest) {
        Map<String, String> inputs1 = talkRequest.getInputs();
        if (inputs1 != null) {
            int aiTypeId = talkRequest.getAiTypeId();
            if (aiTypeId == 1 || aiTypeId == 2) {
                ModuleCreateReq.Inputs moduleCreateInput = new ModuleCreateReq.Inputs();
                ModuleCreateReq moduleCreateReq = new ModuleCreateReq();
                moduleCreateReq.setQuery(talkRequest.getQuery());
                moduleCreateReq.setConversation_id(talkRequest.getConversation_id());
                moduleCreateInput.setIndustry(inputs1.get("industry"));
                moduleCreateInput.setProduct(inputs1.get("product"));
                moduleCreateInput.setEnterpriseScale(inputs1.get("enterpriseScale"));
                moduleCreateReq.setInputs(moduleCreateInput);
                moduleCreateReq.setUser( userProvider.get().getUserId());
                return moduleCreateReq;
            } else if (aiTypeId == 3) {
                DoCreateReq.Inputs doCreateReqInput = new DoCreateReq.Inputs();
                DoCreateReq doParamReq = new DoCreateReq();
                doCreateReqInput.setDoName(inputs1.get("doName"));
                doParamReq.setQuery(talkRequest.getQuery());
                doParamReq.setInputs(doCreateReqInput);
                doParamReq.setUser( userProvider.get().getUserId());
;
                return doParamReq;
            }else{
                StreamReq streamReq = new StreamReq();
                streamReq.setQuery(talkRequest.getQuery());
                streamReq.setConversation_id(talkRequest.getConversation_id());
                streamReq.setUser( userProvider.get().getUserId());
;
                return streamReq;
            }
        }
        return null;
    }

    /**
     *  @deprecated 改为流式请求
     */
    @Deprecated
    public AnalyzeResult manageCreateAi(ModuleCreateReq moduleCreateReq) throws Exception {
        String userid =  "admin";
        moduleCreateReq.setUser(userid);
        String txt = DifyApiReqUtil.sendApiReq(API_BASE_URL, manageModuleCreateAI, DifyApiEnum.CREATE_CHAT_MESSAGE, null, moduleCreateReq, userProvider.get().getUserId());
        String[] split = txt.split("\n");
        List<String> list = new ArrayList<>();
        Collections.addAll(list, split);
        for (int i = 0; i < list.size(); i++) {
            String s = list.get(i);

        }
        String thoughtJson = "";
        for (String res : list) {
            if (StrUtil.isEmpty(res)) {
                continue;
            }
            String resultString = res.trim().replaceFirst("^data:", "");
            if (JsonUtils.keyExists(resultString, "$.event")) {
                String event = JsonPath.read(resultString, "$.event");
                if ("agent_thought".equals(event)) {
                    thoughtJson = resultString;
                } else if ("message_end".equals(event)) {
                    if (JsonUtils.keyExists(resultString, "$.status")) {
                        int statusValue = JsonPath.read(resultString, "$.status");
                        if (statusValue != 200) {
                            AnalyzeResult analyzeResult = new AnalyzeResult();
                            analyzeResult.setCode(statusValue);
                            if (JsonUtils.keyExists(resultString, "$.message")) {
                                String message = JsonPath.read(resultString, "$.message");
                                analyzeResult.setMsg(message);
                                return analyzeResult;
                            } else {
                                analyzeResult.setMsg("DIFY对话功能异常");
                                return analyzeResult;
                            }
                        }
                    }
                }
            }
        }
        Gson gson = new Gson();
        DifyThoughtResp difyThoughtResp = gson.fromJson(thoughtJson, DifyThoughtResp.class);
        log.info("DIFY resp obj{}", difyThoughtResp);
        String thought = difyThoughtResp.getThought();
        thought = thought.replaceFirst("```markdown", "");
        List<ModuleData> flatNodes = ResultHandleUtil.parseMarkdownList(thought);
        List<ModuleData> treeNodes = ResultHandleUtil.buildTree(flatNodes);
        AnalyzeResult analyzeResult = new AnalyzeResult();
        analyzeResult.setTalkValue(thought);
        analyzeResult.setConversationId(difyThoughtResp.getConversation_id());
        analyzeResult.setTalkType(0);
        analyzeResult.setCode(200);
        return analyzeResult;
    }

//    /**
//     *  @deprecated 改为流式请求
//     */
//    @Deprecated
//    public AnalyzeResult doCreateAi(DoCreateReq moduleTalkReq) throws IOException {
//        moduleTalkReq.setUser( userProvider.get().getUserId());
//;
//        String userid =  "admin";
//        moduleTalkReq.setUser(userid);
//        String txt = AiApiReqUtil.sendRequest(API_BASE_URL, techModuleCreateAI, DifyApiEnum.CREATE_CHAT_MESSAGE, null, moduleTalkReq, userProvider.get().getUserId());
//        String[] line = txt.split("\n");
//        List<String> list = new ArrayList<>();
//        Collections.addAll(list, line);
//
//        for (int i = 0; i < list.size(); i++) {
//            String s = list.get(i);
//            System.out.println(i);
//            System.out.println(s);
//        }
//        String thoughtJson = "";
//        for (String res : list) {
//            if (StrUtil.isEmpty(res)) {
//                continue;
//            }
//            String resultString = res.trim().replaceFirst("^data:", "");
//            if (JsonUtils.keyExists(resultString, "$.event")) {
//                String event = JsonPath.read(resultString, "$.event");
//                if ("agent_thought".equals(event)) {
//                    thoughtJson = resultString;
//                } else if ("message_end".equals(event)) {
//                    if (JsonUtils.keyExists(resultString, "$.status")) {
//                        int statusValue = JsonPath.read(resultString, "$.status");
//                        if (statusValue != 200) {
//                            AnalyzeResult analyzeResult = new AnalyzeResult();
//                            analyzeResult.setCode(statusValue);
//                            if (JsonUtils.keyExists(resultString, "$.message")) {
//                                String message = JsonPath.read(resultString, "$.message");
//                                analyzeResult.setMsg(message);
//                                return analyzeResult;
//                            } else {
//                                analyzeResult.setMsg("DIFY对话功能异常");
//                                return analyzeResult;
//                            }
//                        }
//                    }
//                }
//            }
//        }
//        Gson gson = new Gson();
//        DifyThoughtResp difyThoughtResp = gson.fromJson(thoughtJson, DifyThoughtResp.class);
//        log.info("DIFY resp obj{}", difyThoughtResp);
//        String thought = difyThoughtResp.getThought();
//        List<DoData> doDataList = new ArrayList<>();
//        String[] sections = thought.split("\n");
//        DoData currentDoData = null;
//        for (String section : sections) {
//            if (!section.isEmpty()) {
//                section = section.trim();
//                if (section.startsWith("1.") || section.startsWith("2.") || section.startsWith("3.") || section.startsWith("4.") || section.startsWith("5.")) {
//                    if (!section.contains("|")) {
//                        currentDoData = new DoData();
//                        currentDoData.setType(section);
//                        doDataList.add(currentDoData);
//                    } else {
//                        if (currentDoData == null) {
//                            continue;
//                        }
//                        String[] split = section.split("\\|");
//                        List<DoLine> doLineList = currentDoData.getDoLine();
//                        if (doLineList == null) {
//                            doLineList = new ArrayList<>();
//                        }
//                        DoLine doLine = new DoLine();
//                        if (split.length == 5) {
//                            doLine.setAttributeCode(split[0].trim());
//                            doLine.setAttributeName(split[1].trim());
//                            doLine.setAttributeType(split[2].trim());
//                            doLine.setAttributeValue(split[3].trim());
//                            doLine.setAttributePermission(split[4].trim());
//                            doLineList.add(doLine);
//                        }
//                        currentDoData.setDoLine(doLineList);
//                    }
//                }
//            }
//        }
//        AnalyzeResult analyzeResult = new AnalyzeResult();
//        analyzeResult.setTalkValue(thought);
//        analyzeResult.setDoShowList(doDataList);
//        analyzeResult.setConversationId(difyThoughtResp.getConversation_id());
//        analyzeResult.setTalkType(1);
//        analyzeResult.setCode(200);
//        return analyzeResult;
//    }
//    /**
//     *  @deprecated 改为流式请求
//     */
//    @Deprecated
//    public AnalyzeResult createChatMessageDoQuery(DoCreateReq moduleTalkReq) throws IOException {
//        moduleTalkReq.setUser( userProvider.get().getUserId());
//;
//        String txt = AiApiReqUtil.sendRequest(API_BASE_URL, doCreateAI, DifyApiEnum.CREATE_CHAT_MESSAGE, null, moduleTalkReq, userProvider.get().getUserId());
//        String[] split = txt.split("\n");
//        List<String> list = new ArrayList<>();
//        Collections.addAll(list, split);
//
//        String thoughtJson = "";
//        for (String res : list) {
//            if (StrUtil.isEmpty(res)) {
//                continue;
//            }
//            String resultString = res.trim().replaceFirst("^data:", "");
//            if (JsonUtils.keyExists(resultString, "$.event")) {
//                String event = JsonPath.read(resultString, "$.event");
//                if ("agent_thought".equals(event)) {
//                    thoughtJson = resultString;
//                } else if ("message_end".equals(event)) {
//                    if (JsonUtils.keyExists(resultString, "$.status")) {
//                        int statusValue = JsonPath.read(resultString, "$.status");
//                        if (statusValue != 200) {
//                            AnalyzeResult analyzeResult = new AnalyzeResult();
//                            analyzeResult.setCode(statusValue);
//                            if (JsonUtils.keyExists(resultString, "$.message")) {
//                                String message = JsonPath.read(resultString, "$.message");
//                                analyzeResult.setMsg(message);
//                                return analyzeResult;
//                            } else {
//                                analyzeResult.setMsg("DIFY对话功能异常");
//                                return analyzeResult;
//                            }
//                        }
//                    }
//                }
//            }
//        }
//        Gson gson = new Gson();
//        DifyThoughtResp difyThoughtResp = gson.fromJson(thoughtJson, DifyThoughtResp.class);
//        log.info("DIFY resp obj{}", difyThoughtResp);
//        StringBuffer stringBuffer = new StringBuffer();
//        String thought = difyThoughtResp.getThought();
//        if (thought.contains("```markdown")) {
//            for (String s : thought.split("\n")) {
//                s = s.trim();
//                if (!s.startsWith("```")) {
//                    stringBuffer.append(s);
//                }
//            }
//        }
//        AnalyzeResult analyzeResult = new AnalyzeResult();
//        analyzeResult.setTalkValue(stringBuffer.toString());
//        analyzeResult.setConversationId(difyThoughtResp.getConversation_id());
//        analyzeResult.setTalkType(0);
//        analyzeResult.setCode(200);
//        return analyzeResult;
//    }
}
